const sqlite3 = require('sqlite3').verbose()
const bcrypt = require('bcrypt')
const path = require('path')

const dbPath = path.join(__dirname, 'novel_platform.db')

async function addTestUsers () {
  console.log('📝 添加测试用户到数据库...\n')

  const db = new sqlite3.Database(dbPath)

  // 测试用户数据
  const testUsers = [
    {
      username: 'admin',
      email: 'admin@novel.com',
      password: 'admin123',
      role: 'admin',
      vip_level: 3,
      is_active: 1,
      reading_time: 120,
      favorite_count: 25
    },
    {
      username: 'user1',
      email: 'user1@test.com',
      password: 'password123',
      role: 'user',
      vip_level: 1,
      is_active: 1,
      reading_time: 45,
      favorite_count: 8
    },
    {
      username: 'user2',
      email: 'user2@test.com',
      password: 'password123',
      role: 'user',
      vip_level: 2,
      is_active: 1,
      reading_time: 89,
      favorite_count: 15
    },
    {
      username: 'vipuser',
      email: 'vip@novel.com',
      password: 'vip123',
      role: 'user',
      vip_level: 3,
      is_active: 1,
      reading_time: 200,
      favorite_count: 50
    },
    {
      username: 'inactive_user',
      email: 'inactive@test.com',
      password: 'inactive123',
      role: 'user',
      vip_level: 0,
      is_active: 0,
      reading_time: 10,
      favorite_count: 2
    }
  ]

  try {
    // 首先检查users表是否存在
    await new Promise((resolve, reject) => {
      db.get(
        "SELECT name FROM sqlite_master WHERE type='table' AND name='users'",
        (err, row) => {
          if (err) reject(err)
          else if (!row) {
            // 创建users表
            const createTableSQL = `
            CREATE TABLE users (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              username TEXT UNIQUE NOT NULL,
              email TEXT UNIQUE NOT NULL,
              password TEXT NOT NULL,
              role TEXT DEFAULT 'user',
              vip_level INTEGER DEFAULT 0,
              is_active INTEGER DEFAULT 1,
              reading_time INTEGER DEFAULT 0,
              favorite_count INTEGER DEFAULT 0,
              created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
              updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
          `
            db.run(createTableSQL, err => {
              if (err) reject(err)
              else {
                console.log('✅ 创建users表成功')
                resolve()
              }
            })
          } else {
            console.log('✅ users表已存在')
            resolve()
          }
        }
      )
    })

    // 添加用户
    for (const user of testUsers) {
      try {
        // 检查用户是否已存在
        const existingUser = await new Promise((resolve, reject) => {
          db.get(
            'SELECT id FROM users WHERE email = ?',
            [user.email],
            (err, row) => {
              if (err) reject(err)
              else resolve(row)
            }
          )
        })

        if (existingUser) {
          console.log(`⚠️  用户 ${user.email} 已存在，跳过`)
          continue
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(user.password, 10)

        // 插入用户
        await new Promise((resolve, reject) => {
          const insertSQL = `
            INSERT INTO users (username, email, password, role, vip_level, is_active, reading_time, favorite_count)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
          `
          db.run(
            insertSQL,
            [
              user.username,
              user.email,
              hashedPassword,
              user.role,
              user.vip_level,
              user.is_active,
              user.reading_time,
              user.favorite_count
            ],
            function (err) {
              if (err) reject(err)
              else {
                console.log(`✅ 添加用户: ${user.email} (${user.role})`)
                resolve()
              }
            }
          )
        })
      } catch (error) {
        console.error(`❌ 添加用户 ${user.email} 失败:`, error.message)
      }
    }

    // 显示用户统计
    const stats = await new Promise((resolve, reject) => {
      db.all(
        `
        SELECT 
          COUNT(*) as total,
          SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
          SUM(CASE WHEN vip_level > 0 THEN 1 ELSE 0 END) as vip,
          SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin
        FROM users
      `,
        (err, rows) => {
          if (err) reject(err)
          else resolve(rows[0])
        }
      )
    })

    console.log('\n📊 用户统计:')
    console.log(`   总用户数: ${stats.total}`)
    console.log(`   活跃用户: ${stats.active}`)
    console.log(`   VIP用户: ${stats.vip}`)
    console.log(`   管理员: ${stats.admin}`)

    console.log('\n🎉 测试用户添加完成！')
  } catch (error) {
    console.error('❌ 添加测试用户失败:', error.message)
  } finally {
    db.close()
  }
}

// 运行脚本
addTestUsers()
